import requests
import json
import random
from dateutil.parser import isoparse

from datetime import datetime, timedelta
from odoo import fields, models, api
from odoo.exceptions import UserError


class RPHolidayTemplate(models.Model):
    _name = "rp.holiday.template"
    _description = '节假日模版'

    name = fields.Char(string='名称', required=True)
    year = fields.Char(string='年', required=True)
    rp_week_template_lines = fields.One2many(string='双休模版明细', comodel_name='rp.holiday.template.line', inverse_name='rp_holiday_template_id', domain=[('type', '=', 'week')])
    rp_holiday_template_lines = fields.One2many(string='假日模版明细', comodel_name='rp.holiday.template.line', inverse_name='rp_holiday_template_id', domain=[('type', '=', 'holiday')])
    
    def one_click_empty(self):
        lines = self.rp_holiday_template_lines + self.rp_week_template_lines
        for line in lines:
            line.unlink()
    
    def catch_url_from_baidu(self, calcultaion_year, month, dataTime):   
        headers = {"Content-Type": "application/json;charset=UTF-8"}
        param = {
                "query": str(calcultaion_year) + "年" + str(month) + "月",
                "resource_id": "39043",
                "t": dataTime,
                "ie": "utf8",
                "oe": "gbk",
                "format": "json",
                "tn": "wisetpl",
                "cb": ""
            }
        r = requests.get(url="https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php", headers=headers,
                            params=param).text
        month_data = json.loads(r)["data"][0]["almanac"]
        return month_data

    def deal_datas(self, year, month_datas):
        def start_time(oDate, type):
            str_date = oDate.split("T")[0]
            if type == "start":
                res_date = datetime.strptime(str_date, '%Y-%m-%d') + timedelta(days=1)
            else:
                res_date = datetime.strptime(str_date, '%Y-%m-%d') + timedelta(days=2)

            return res_date

        i = 0
        for month_data in month_datas:
            if month_data["cnDay"] == '六':
                i += 1
                self.env['rp.holiday.template.line'].create({
                    'rp_holiday_template_id': self.id,
                    'name': '第'+str(i)+'周',
                    'type': 'week',
                    'start_time': start_time(month_data["oDate"], type="start"),
                    'end_time': start_time(month_data["oDate"], type="end")
                })
            holiday_list = ['圣诞节','劳动节']
            for holiday in holiday_list:
                if month_data.get('festivalList'):
                    if holiday in month_data.get('festivalList'):
                        self.env['rp.holiday.template.line'].create({
                            'rp_holiday_template_id': self.id,
                            'name': holiday,
                            'type': 'holiday',
                            'start_time': start_time(month_data["oDate"], type="start"),
                            'end_time': start_time(month_data["oDate"], type="end")
                        })
    
    def one_click_fill(self):
        dataTime = str(random.random())
        month_datas = []
        for i in [2,5,8,11]:
            month_data = self.catch_url_from_baidu(self.year, i, dataTime)
            month_datas += month_data
        self.deal_datas(self.year, month_datas)
    
    
class RPHolidayTemplateLine(models.Model):
    _name = "rp.holiday.template.line"
    _description = '节假日模版明细'
    _order = "start_time"

    rp_holiday_template_id = fields.Many2one(string='节假日模版', comodel_name='rp.holiday.template', ondelete='cascade')
    rp_courier_id = fields.Many2one(string='承运商', comodel_name='rp.courier', ondelete='cascade')
    name = fields.Char(string='名称', required=True)
    type = fields.Selection(string='类型', selection=[('week', '双休'),
                                                     ('holiday', '节日')], default='week', required=True)
    start_time = fields.Date(string='开始时间', required=True)
    end_time = fields.Date(string='结束时间', required=True)
    day_length = fields.Integer(string='时长', compute='_compute_day_length')
    
    @api.depends('start_time','end_time')
    def _compute_day_length(self):
        for rec in self:
            if rec.start_time and rec.end_time:
                rec.day_length = (rec.end_time - rec.start_time).days + 1
            else:
                rec.day_length = 0
    
    # 定期清理无用的节假日明细，防止数据冗余
    def clear_datas(self):
        lines = self.search([('rp_holiday_template_id','=',False),('rp_courier_id','=',False)])
        for line in lines:
            line.unlink()
